/**
 * 
 */
package br.com.ufc.apsoo.hotelar.dao.impl;

import java.util.Date;
import java.util.List;

import org.hibernate.Session;
import org.hibernate.Transaction;

import br.com.ufc.apsoo.hotelar.dao.HospedagemDao;
import br.com.ufc.apsoo.hotelar.model.Cliente;
import br.com.ufc.apsoo.hotelar.model.Hospedagem;
import br.com.ufc.apsoo.hotelar.utils.HibernateUtil;

/**
 * @author Virginia
 *
 */
public class HospedagemDaoImpl implements HospedagemDao {

	@Override
	public void save(Hospedagem hospedagem) {
		Session session = HibernateUtil.getSession();
		Transaction t = session.beginTransaction();
		session.save(hospedagem);
		t.commit();
		session.close();		
	}

	@Override
	public void remove(Hospedagem hospedagem) {
		Session session = HibernateUtil.getSession();
		Transaction t = session.beginTransaction();
		session.delete(hospedagem);
		t.commit();
		session.close();		
	}

	@Override
	public void update(Hospedagem hospedagem) {
		Session session = HibernateUtil.getSession();
		Transaction t = session.beginTransaction();
		session.update(hospedagem);
		t.commit();
		session.close();		
	}

	@Override
	public Hospedagem getHospedagemById(int id) {
		Session session = HibernateUtil.getSession();
		try {
			return (Hospedagem) session.get(Hospedagem.class, id);
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			session.close();
		}
		return null;
	}

	@SuppressWarnings("unchecked")
	@Override
	public List<Hospedagem> list() {
		Session session = HibernateUtil.getSession();
		try {
			return session.createCriteria(Hospedagem.class).list();
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			session.close();
		}
		return null;
	}

	@Override
	public Hospedagem getHospedagemAtivaByCliente(Cliente cliente) {
		Session session = HibernateUtil.getSession();
		String query = "from Hospedagem where cliente = :cliente and status = true";
		try {
			return (Hospedagem) session.createQuery(query).setInteger("cliente", cliente.getId()).uniqueResult();
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			session.close();
		}
		return null;
	}

	@SuppressWarnings("unchecked")
	@Override
	public List<Hospedagem> getHospedagensByData(Date data) {
		Session session = HibernateUtil.getSession();
		String query = "from Hospedagem h where :data BETWEEN h.periodo.inicio AND h.periodo.fim";
		try {
			return session.createQuery(query).setDate("data", data).list();
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			session.close();
		}
		return null;
	}

}
